/**
 * Created by gongxun on 17/1/18.
 */

var PdkTableStatus = function () {
    var that = {};

    //牌桌映像
    that.mTableStatus = null;

    //录像msg
    that.replayMsgs = null;

    //录像type
    that.replayTypes = null;

    //是否是断线重练
    that.isReconnect = false;

    //自己可以出牌的数组
    that.myCanPlayCardss = null;

    //牌桌结算印象
    that.mTableResults = [];

    //设置牌桌映像
    that.setTableStatus = function (tableStatus) {
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step != 0) {
            that.isReconnect = false;
        }

        //在牛牛里面才触发
        if (mo.sceneHelper.currentLayerName != "pdk") {
            return;
        }

        that.updateTableStatus();
    };

    that.setReconnectStatus = function (tableStatus) {
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step == 0) {
            that.isReconnect = true;
        }

        //更新用户信息
        that.updateUserInfo();

        that.updateStep();

        //断线重连
        that.setReconnet();

        //ui状态
        that.setUIShowStatus();
    };

    that.updateTableStatus = function () {
        //更新用户信息
        that.updateUserInfo();

        that.updateStep();

        //ui状态
        that.setUIShowStatus();

        //播放音效
        that.playMusic();
    };

    that.updateUserInfo = function () {
        //牌局结束以后（剩余次数为0，step为0） 不显示用户ui变化
        if (that.mTableStatus.LeftPlayTimes == 0 && that.mTableStatus.Step == 0) {
            return;
        }

        //收到大结算了 不处理用户变化
        if (mo.pdkTable.mPdkTableRoomEndLayer != null) {
            return;
        }

        if (that.mTableStatus.TableID) {
            var infos = [null, null, null];
            for (var seat = 0; seat < 3; seat++) {
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                infos[seat] = that.mTableStatus["SeatUser" + (logicSeat + 1)];
            }
            mo.pdkTable.mPdkTableUILayer.setTablePlayerInfos(infos);
        } else {
            //录像可能没有
        }
    };

    //更新牌局信息
    that.updateStep = function () {
        if (that.mTableStatus.Step == 0) {

        } else if (that.mTableStatus.Step == 1) {
            //开始打牌
            if (that.mTableStatus.LastAction == null) {
                //发牌
                var numss = [];
                for (var seat = 0; seat < 3; seat++) {
                    var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                    numss.push(that.mTableStatus["SeatUser" + (logicSeat + 1)].HandCards);
                }
                mo.pdkTable.setFapaiAnim(numss);
                mo.soundHelper.playStartGame();
            }

            var currentSeat = that.getCurrentPlayerSeat();
            var mySeatUser = that.getMySeatUser();

            //显示打出牌
            var dealCardNumss = [null, null, null];
            //最新大出牌的座位号
            var LastDealSeat = -1;
            for (var seat = 0; seat < 3; seat++) {
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1) + 1;
                var seatUser = that.mTableStatus["SeatUser" + logicSeat];
                if (seatUser == null || currentSeat == seat || seatUser.OldActionList.length == 0) {
                    //当前操作玩家不显示历史数据
                    continue;
                }

                if (seatUser.OldActionList[0].code == 0) {
                    //出牌
                    dealCardNumss[seat] = seatUser.OldActionList[0].Cards;
                } else if (seatUser.OldActionList[0].code == 1) {
                    //放弃
                    dealCardNumss[seat] = [];
                }

                if (logicSeat == that.mTableStatus.LastActionSeat) {
                    LastDealSeat = seat;
                }
            }
            mo.pdkTable.setChupai(dealCardNumss, LastDealSeat);

            //移除自己的手牌
            if (that.mTableStatus.LastAction != null && that.mTableStatus.LastAction.code == 0) {
                var dealCardNums = that.mTableStatus.LastAction.Cards;
                var dealSeat = that.getViewForLogic(that.mTableStatus.LastActionSeat - 1, that.mTableStatus.MySeat - 1);
                mo.pdkTable.setDealCardNums(dealCardNums, dealSeat);
            }

            //是否是自己打牌 自己打的话计算能否出牌 不能的话 直接放弃
            if (currentSeat == 0) {
                var isMyFrist = false;
                var isCanPlay = false;
                if (that.mTableStatus.LastAction == null || that.mTableStatus.LastPlayCardsSeat == that.mTableStatus.MySeat) {
                    isMyFrist = true;
                    isCanPlay = true;
                } else {
                    //别人的牌
                    var oldActionList = that.mTableStatus["SeatUser" + that.mTableStatus.LastPlayCardsSeat].OldActionList;
                    var otherNums = oldActionList[oldActionList.length - 1].Cards;

                    var myNums = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat].HandCards;
                    that.myCanPlayCardss = mo.pdkCardRule.checkCanPlay(otherNums, myNums);

                    //下家保单了 如果出得是单张 要过滤一次
                    if (that.mTableStatus["SeatUser" + (that.mTableStatus.MySeat % 3 + 1)].LeftCards == 1 && otherNums.length == 1){
                        //过滤到 只剩下最大的单张手牌
                        var myMaxInhandCardNums = -1;
                        for (var i = 0; i < that.myCanPlayCardss.length;){
                            var myCanPlayCards = that.myCanPlayCardss[i];
                            if (myCanPlayCards.length == 1){
                                //记录
                                if (myCanPlayCards[0] > myMaxInhandCardNums){
                                    myMaxInhandCardNums = myCanPlayCards[0];
                                }

                                that.myCanPlayCardss.splice(i, 1);
                            }else{
                                i++;
                            }
                        }
                        if (myMaxInhandCardNums != -1){
                            that.myCanPlayCardss.splice(0, 0, [myMaxInhandCardNums]);
                        }
                    }

                    if (that.myCanPlayCardss.length > 0) {
                        isCanPlay = true;
                        cc.log("自己要得起");
                    } else {
                        isCanPlay = false;
                        cc.log("自己要不起");
                    }
                }

                mo.pdkTable.mPdkTableUILayer.updateTishiStatus(isMyFrist, isCanPlay);

                //每回合开始 检测出牌选项
                that.checkSelectIsPlay();
            }

            //如有人打牌 显示动画
            if (that.mTableStatus.LastAction != null){
                if (that.mTableStatus.LastAction.code == 0){
                    var seatUser = that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat];
                    var viewSeat = that.getViewForLogic(that.mTableStatus.LastActionSeat - 1, that.mTableStatus.MySeat - 1);
                    if (seatUser.LeftCards == 0){
                        //播放赢
                        mo.pdkTable.mPdkTableCardLayer.playWinAnim(viewSeat);

                    }else if (seatUser.LeftCards == 1){
                        //播放保单
                        mo.pdkTable.mPdkTableCardLayer.playBaodanAnim(viewSeat);

                    }
                }
            }
        }
    };

    that.setReconnet = function () {
        var tableStatus = mo.pdkTableStatus.mTableStatus;

        //inhandCard
        if (that.mTableStatus.Step == 1) {
            var numss = [];
            for (var seat = 0; seat < 3; seat++) {
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                numss.push(that.mTableStatus["SeatUser" + (logicSeat + 1)].HandCards);
            }
            mo.pdkTable.mPdkTableCardLayer.removeAllCards();
            mo.pdkTable.mPdkTableCardLayer.setInhandCard(numss);

            var currentSeat = that.getCurrentPlayerSeat();

            //显示打出牌
            var dealCardNumss = [null, null, null];
            for (var seat = 0; seat < 3; seat++) {
                var seatUser = that.mTableStatus["SeatUser" + (that.getLogicForView(seat, that.mTableStatus.MySeat - 1) + 1)];
                if (seatUser == null || currentSeat == seat || seatUser.OldActionList.length == 0) {
                    //当前操作玩家不显示历史数据
                    continue;
                }

                if (seatUser.OldActionList[0].code == 0) {
                    //出牌
                    dealCardNumss[seat] = seatUser.OldActionList[0].Cards;
                } else if (seatUser.OldActionList[0].code == 1) {
                    //放弃
                    dealCardNumss[seat] = [];
                }
            }
            mo.pdkTable.setChupai(dealCardNumss);
        }

        mo.pdkTable.updateLastPlayTimes();
    };

    //设置ui该显示的状态
    that.setUIShowStatus = function () {
        if (that.mTableStatus.Step == 0) {
            //非牌局
            mo.pdkTable.mPdkTableUILayer.intoShowIndex(11);

            mo.pdkTable.updateLastPlayTimes();
        } else if (that.mTableStatus.Step == 1) {
            //开始打牌了
            if (that.mTableStatus.NowSeat.length == 1 && that.mTableStatus.NowSeat[0] == that.mTableStatus.MySeat) {
                mo.pdkTable.mPdkTableUILayer.intoShowIndex(20);
            } else {
                mo.pdkTable.mPdkTableUILayer.intoShowIndex(21);
            }

        }

        //更新该谁打牌
        mo.pdkTable.mPdkTableUILayer.setPlayerTime(that.getCurrentPlayerSeat(), that.mTableStatus.Step);
    };

    //检测能否出牌
    that.checkSelectIsPlay = function () {
        if (that.mTableStatus == null) {
            return;
        }

        //自己出牌结算
        if (that.mTableStatus.Step == 1 && that.mTableStatus.NowSeat.length == 1 && that.mTableStatus.NowSeat[0] == that.mTableStatus.MySeat) {

            //自己的手牌
            var myInhandCards = that.getMySeatUser().HandCards;
            //选择的牌
            var myCardNums = mo.pdkTable.mPdkTableCardLayer.mPlayers[0].getUpCardNums();

            //检测牌型
            var myCardType = mo.pdkCardRule.checkCardType(myCardNums);
            var okCardRules = mo.pdkCardRule.GetCardTypesForRule(mo.pdkTable.mGameConfig);
            if (myCardType == CardType.error) {
                cc.log("牌型错误");
                mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                return;
            }else if (mo.gameHelper.findValueForArray(okCardRules, myCardType) == null){
                cc.log("牌型不符合规则");
                // mo.showRoomMsgShow("牌型不符合规则");
                mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                return;
            }

            //确保下家是保单
            var lastPlaySeat = that.mTableStatus.MySeat % 3 + 1;
            var lastCardNumsLength = that.mTableStatus["SeatUser" + lastPlaySeat].LeftCards;
            if (!mo.pdkCardRule.checkIsPlaySing(myInhandCards, lastCardNumsLength, myCardNums)) {
                mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                return;
            }

            if (that.mTableStatus.LastAction == null || that.mTableStatus.LastPlayCardsSeat == that.mTableStatus.MySeat) {
                //自己只出牌 不接牌的情况
                //自己是首轮出牌 要检查规则
                //赢家先出的首局必须红桃三先出 但是要见红桃三
                if (mo.pdkTable.mGameConfig.hosttype == 1 && that.mTableStatus.LeftPlayTimes == mo.pdkTable.mGameConfig.maxpan && that.getIsALlPlayerNotPlay() && !mo.pdkCardRule.checkCardNumIncludeNum(myCardNums, 16)) {
                    // mo.showRoomMsgShow("赢家先出规则 首局必须出带红桃三的牌型");
                    mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                    return;
                }

                // //检查特殊牌型能否打出
                // if (myCardType == CardType.triple && myInhandCards.length != myCardNums.length ||
                //     myCardType == CardType.tripleSingle && myInhandCards.length != myCardNums.length ||
                //     myCardType == CardType.airplaneEx && myInhandCards.length != myCardNums.length
                // ) {
                //     mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                //     return;
                // }
            }
            else {
                //管别人的牌
                //别人的牌
                var oldActionList = that.mTableStatus["SeatUser" + that.mTableStatus.LastPlayCardsSeat].OldActionList;
                var otherNums = oldActionList[oldActionList.length - 1].Cards;

                if (!mo.pdkCardRule.checkCardTypePlay(otherNums, myCardNums)) {
                    mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(false);
                    return;
                }
            }

            mo.pdkTable.mPdkTableUILayer.updateChupaiBtnStatus(true);
        }
    }
    ;

    //推荐出牌
    that.setTuiJianChuPai = function (index) {
        if (that.mTableStatus.Step == 1 && that.mTableStatus.NowSeat.length == 1 && that.mTableStatus.NowSeat[0] == that.mTableStatus.MySeat) {
            if (that.mTableStatus.LastAction == null || that.mTableStatus.LastPlayCardsSeat == that.mTableStatus.MySeat) {
                cc.log("自己先出牌");
            } else {
                if (that.myCanPlayCardss == null || that.myCanPlayCardss.length == 0) {
                    that.onGiveUp();
                } else {
                    if (index != null) {
                        var curIndex = index % that.myCanPlayCardss.length;
                        var tuijianZhi = that.myCanPlayCardss[curIndex];
                        // mo.showRoomMsgShow("推荐出牌值:" + tuijianZhi.valueOf());
                        cc.log("推荐出牌值:" + tuijianZhi.valueOf());

                        var myNums = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat].HandCards;
                        var tuijianCards = mo.pdkCardRule.getCardNumsForZhiNums(tuijianZhi, myNums);
                        if (tuijianCards.length != 0) {
                            mo.pdkTable.mPdkTableCardLayer.mPlayers[0].selectCardTuijian(tuijianCards);
                        }
                    }
                }
            }
        }

    };

    //出牌
    that.onPlayCard = function () {
        if (that.mTableStatus.Step == 1 && that.getCurrentPlayerSeat() == 0) {
            var isPlay = false;
            var seatUser = that.getMySeatUser();
            for (var i = 0; i < seatUser.NewActionList.length; i++) {
                if (seatUser.NewActionList[i].code == 0) {
                    isPlay = true;
                    break;
                }
            }
            if (isPlay) {
                var nums = mo.pdkTable.mPdkTableCardLayer.mPlayers[0].getUpCardNums();
                mo.gameMsgManager.sendActionRequestpdk(0, nums);
            }
        }
    };

    //放弃出牌
    that.onGiveUp = function () {
        if (that.mTableStatus.Step == 1 && that.getCurrentPlayerSeat() == 0) {
            var isGiveUp = false;
            var seatUser = that.getMySeatUser();
            for (var i = 0; i < seatUser.NewActionList.length; i++) {
                if (seatUser.NewActionList[i].code == 1) {
                    isGiveUp = true;
                    break;
                }
            }
            if (isGiveUp) {
                mo.gameMsgManager.sendActionRequestpdk(1, []);
            }
        }
    };

    //是否所有玩家都没有出牌
    that.getIsALlPlayerNotPlay = function () {
        if (that.mTableStatus.Step == 1) {
            for (var i = 0; i < 3; i++) {
                if (that.mTableStatus["SeatUser" + (i + 1)].LeftCards != 16) {
                    return false;
                }
            }
        }

        return true;
    };

    //处理货币结算
    that.handlerTableResult = function(){
        if (that.mTableResults.length != 0){
            var scores = [0, 0, 0];
            for (var i = 0; i < that.mTableResults.length; i++){
                var item = that.mTableResults[i];
                if (
                    item.ResultType == 1
                ){
                    var addSeat = that.getViewForLogic(item.ToSeat - 1, that.mTableStatus.MySeat - 1);
                    var subSeat = that.getViewForLogic(item.FromSeat - 1, that.mTableStatus.MySeat - 1);
                    var score = item.PayMoney;
                    scores[addSeat] += score;
                    scores[subSeat] -= score;
                }
            }
            that.mTableResults.splice(0, that.mTableResults.length);

            mo.pdkTable.setResultScore(scores);
        }
    };

    //播放音效
    that.playMusic = function () {
        if (that.mTableStatus == null || that.mTableStatus.Step != 1) {
            return;
        }

        var LastAction = that.mTableStatus.LastAction;
        if (LastAction == null) {
            return;
        }

        var sex = 0;
        if (that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat] != null && that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info != null) {
            sex = that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].user_info.sex;
        }

        if (LastAction.code == 1) {
            mo.soundHelper.playPdkYaobuqi(sex);
        } else if (LastAction.code == 0) {
            var cardNums = LastAction.Cards;
            var cardType = mo.pdkCardRule.getCardType(cardNums);

            //默认音效
            var defaultCardType = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
            if (mo.gameHelper.findValueForArray(defaultCardType, cardType) != null) {
                mo.soundHelper.playPdkCardTypeSound(sex, cardType);
            } else {
                if (cardType == 1) {
                    //单张
                    mo.soundHelper.playPdkSingle(sex, cardNums[0]);
                } else if (cardType == 2) {
                    mo.soundHelper.playPdkPair(sex, cardNums[0]);
                } else if (cardType == 3) {
                    mo.soundHelper.playPdkTriple(sex, cardNums[0]);
                }
            }

            //自然音效
            if (cardType == 16) {
                mo.soundHelper.playPdkEffectBoom();
            } else if (cardType == 13 || cardType == 14 || cardType == 15) {
                mo.soundHelper.playPdkEffectPlane();
            } else {
                mo.soundHelper.playPdkEffectDeal();
            }

            //操作玩家剩余手牌
            var lastActionLeftCardLen = that.mTableStatus["SeatUser" + that.mTableStatus.LastActionSeat].LeftCards;

            //保单
            if (lastActionLeftCardLen == 1){
                //保单音效
                mo.soundHelper.playPdkBaodan(sex);
            }else if(lastActionLeftCardLen == 0){

                //播放输赢
                mo.soundHelper.playPdkLoseWin(that.mTableStatus.LastActionSeat == that.mTableStatus.MySeat);
            }
        }
    };

    //返回自己的seatuser
    that.getMySeatUser = function () {
        var seatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
        return seatUser;
    };

    //获取自己是否准备
    that.getMyIsReady = function () {
        var seatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
        return seatUser.State == 1;
    };

    //获取玩家同ip信息
    that.getPlayerIpEqual = function () {
        var result = [];

        //记录ip
        var ipStruct = {};
        for (var i = 1; i <= 5; i++) {
            var seatUser = that.mTableStatus["SeatUser" + i];
            if (seatUser != null && seatUser.user_info != null) {
                var userInfo = seatUser.user_info;
                if (mo.gameHelper.getIsJson(userInfo.DeviceJson)) {
                    var deviceJson = JSON.parse(userInfo.DeviceJson);
                    var ip = deviceJson.ip;
                    if (ip != null && ip != "" && ip != "127.0.0.1") {
                        if (ipStruct[ip] == undefined) {
                            ipStruct[ip] = [];
                        }
                        ipStruct[ip].push(userInfo.nickname);
                    }
                }
            }
        }

        //分解出出现两次的用户
        for (var key in ipStruct) {
            if (ipStruct.hasOwnProperty(key)) {
                if (ipStruct[key].length > 1) {
                    var nicks = ipStruct[key];
                    for (var i = 0; i < nicks.length; i++) {
                        var item = {};
                        item.nick = nicks[i];
                        item.ip = key;
                        result.push(item);
                    }
                }
            }
        }

        return result;
    };

    //通过ui的返回玩家视图座位号
    that.getViewSeatForUid = function (uid) {
        var logicIndex = -1;
        for (var i = 0; i < 5; i++) {
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null) {
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid) {
                    logicIndex = i;
                }
            }
        }
        if (logicIndex != -1) {
            return that.getViewForLogic(logicIndex, that.mTableStatus.MySeat - 1);
        } else {
            return -1;
        }
    };

    //通过用户id获取用户性别
    that.getSexForUid = function (uid) {
        var sex = 0;
        for (var i = 0; i < 5; i++) {
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null && seatUser.user_info != null) {
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid) {
                    sex = seatUser.user_info.sex;
                }
            }
        }
        return sex;
    };

    //返回玩家人数
    that.getPlayerCount = function () {
        var count = 0;
        for (var i = 1; i <= 5; i++) {
            var userSeat = that.mTableStatus["SeatUser" + i];
            if (userSeat != null) {
                count++;
            }
        }
        return count;
    };

    that.getCurrentPlayerSeat = function () {
        if (that.mTableStatus.Step == 0) {
            return -1;
        } else {
            if (that.mTableStatus.NowSeat.length == 1) {
                return that.getViewForLogic(that.mTableStatus.NowSeat[0] - 1, that.mTableStatus.MySeat - 1);
            } else {
                return -1;
            }
        }
    };

    //加载录像
    that.setReplayMsg = function (rePlaypdk) {
        that.replayMsgs = [];
        that.replayTypes = [];

        //设置录像时候自己的座位号
        var replayMySeat = 1;
        var roundEndedEvent = rePlaypdk.Result;
        for (var i = 1; i <= 3; i++) {
            if (roundEndedEvent["SeatUser" + i] != null) {
                if (roundEndedEvent["SeatUser" + i].user_info != null) {
                    if (roundEndedEvent["SeatUser" + i].user_info.userid == mo.gameUserInfo.uid) {
                        replayMySeat = i;
                        break;
                    }
                }
            }
        }
        roundEndedEvent.MySeat = replayMySeat;

        //牌桌映像数据
        for (var i = 0; i < rePlaypdk.Images.length; i++) {
            var tableStatspdk = rePlaypdk.Images[i];
            //修改MySeat
            tableStatspdk.MySeat = replayMySeat;

            that.replayMsgs.push(tableStatspdk);
            that.replayTypes.push(2806);
        }

        //牌桌结算数据
        that.replayMsgs.push(rePlaypdk.Result);
        that.replayTypes.push(2808);
    };

    //播放录像
    that.playReplay = function () {
        if (that.replayMsgs.length > 0) {
            var msg = that.replayMsgs.shift();
            var type = that.replayTypes.shift();

            var response = null;
            if (type == 2806) {
                //牌桌映象
                response = new PdkTableStatspdk();

            } else if (type == 2808) {
                //牌桌结算
                response = new PdkRoundEndedEventpdk();

            }

            if (response) {
                response.handleMsg(msg);
                response.log();
            } else {
                cc.warn("type:" + type + "未注册");
            }
            return true;
        } else {
            cc.log("录像播放完毕");
            return false;
        }

    };

    that.getLogicForView = function (view, myLogicSeat) {
        var logic = (view + 3 + myLogicSeat) % 3;
        return logic;
    };

    that.getViewForLogic = function (logic, myLogicSeat) {
        var view = (logic + 3 - myLogicSeat) % 3;
        return view;
    };

    return that;
};

mo.pdkTableStatus = new PdkTableStatus();